package web.common.internal.jdo.engine;

import org.springframework.jdbc.core.PreparedStatementCreator;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.List;

/**
 * @author Jin Zheng
 * @since 1.0 2022-01-13
 */
public class DefaultPreparedStatementCreator implements PreparedStatementCreator {
	private final String sql;
	private final List<?> paramList;

	public DefaultPreparedStatementCreator(String sql, List<?> paramList) {
		this.sql = sql;
		this.paramList = paramList;
	}

	@Override
	public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
		var pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
		this.setParams(pstmt, paramList);
		return pstmt;
	}

	private void setParams(PreparedStatement pstmt, Collection<?> list) throws SQLException {
		if (list == null || list.isEmpty()) {
			return;
		}

		int i = 1;
		for (Object obj : list) {
			if (obj == null) {
				pstmt.setObject(i, null);
				continue;
			}

			pstmt.setObject(i, obj);
			i++;
		}
	}
}
